import { defineStore } from 'pinia'
import { ref } from 'vue'
import { listAdminApi, addAdminApi, editAdminApi, deleteAdminApi } from '@/api/admin'
import { handleApiError, handleSuccess } from '@/utils/errorUtils'

export const useAdminStore = defineStore('admin', () => {
  // 状态定义
  const adminList = ref([])
  const total = ref(0)
  const loading = ref(false)
  const currentAdmin = ref(null)
  const queryParams = ref({ 
    page: 1, 
    limit: 10 
  })

  // 获取管理员列表
  const loadAdminList = async () => {
    try {
      loading.value = true
      const res = await listAdminApi({ 
        page: queryParams.value.page, 
        limit: queryParams.value.limit 
      })
      adminList.value = res.data?.list || res.list || []
      total.value = res.data?.total || res.total || 0
    } catch (error) {
      handleApiError(error, '获取管理员列表失败')
    } finally {
      loading.value = false
    }
  }

  // 添加管理员
  const addAdmin = async (data) => {
    try {
      const result = await addAdminApi(data)
      handleSuccess('添加成功')
      await loadAdminList()
      return result
    } catch (error) {
      handleApiError(error, '添加失败')
      throw error
    }
  }

  // 编辑管理员
  const editAdmin = async (data) => {
    try {
      await editAdminApi(data)
      handleSuccess('更新成功')
      await loadAdminList()
    } catch (error) {
      handleApiError(error, '更新失败')
    }
  }

  // 删除管理员
  const deleteAdmin = async (id) => {
    try {
      await deleteAdminApi({ id })
      handleSuccess('删除成功')
      await loadAdminList()
    } catch (error) {
      handleApiError(error, '删除失败')
    }
  }


  // 更新查询参数
  const updateQueryParams = (params) => {
    queryParams.value = { ...queryParams.value, ...params }
  }

  // 重置查询参数
  const resetQueryParams = () => {
    queryParams.value = { page: 1, limit: 10 }
  }

  return {
    // 状态
    adminList,
    total,
    loading,
    currentAdmin,
    queryParams,
    
    // API方法
    loadAdminList,
    addAdmin,
    editAdmin,
    deleteAdmin,
    
    // 业务方法
    updateQueryParams,
    resetQueryParams
  }
})